import dayjs from 'dayjs'
import rt from 'dayjs/plugin/relativeTime'
import { App } from 'vue'
// 语言包
// import 'dayjs/locale/zh-cn'
import { useStore } from '@/store'
const store = useStore()

export const dateFilter = (val: any, format = 'YYYY-MM-DD') => {
  if (!isNaN(val)) {
    val = parseInt(val)
  }

  return dayjs(val).format(format)
}

// 加载相对时间插件
dayjs.extend(rt)
function relativeTime(val: any) {
  if (!isNaN(val)) {
    val = parseInt(val)
  }
  return dayjs()
    .locale(store?.getters?.language === 'zh' ? 'zh-cn' : 'en')
    .to(dayjs(val))
}

export const formatDate = (numb: any) => {
  const time: any = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  return (
    year +
    '-' +
    (~~month < 10 ? '0' + month : month) +
    '-' +
    (~~date < 10 ? '0' + date : date)
  )
}
export const dateFormat = (dateData: any) => {
  const date = new Date(dateData)
  let y = date.getFullYear()
  let m = ~~(date.getMonth() + 1)
  m = m < 10 ? 0 + m : m
  var d = date.getDate()
  d = d < 10 ? 0 + d : d
  const time = y + '-' + m + '-' + d
  return time
}

export default (app: App) => {
  app.config.globalProperties.$filters = {
    dateFilter,
    relativeTime,
    dateFormat
  }
}
